package com.ruoyi.wechat.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.wechat.domain.Code2Session;
import com.ruoyi.wechat.domain.WechatUser;
import com.ruoyi.wechat.mapper.WechatUserMapper;
import com.ruoyi.wechat.service.IWechatLoginService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class IWechatLoginServiceImpl implements IWechatLoginService {

    @Value("${wechat.miniprogram.auth.code2SessionUrl}")
    private String code2SessionUrl;

    @Value("${wechat.miniprogram.appid}")
    private String appid;

    @Value("${wechat.miniprogram.secret}")
    private String secret;

    private WechatUserMapper wechatUserMapper;

    @Override
    public Code2Session code2Session(String code) {
        String url = code2SessionUrl;
        url = url.replace("APPID",appid);
        url = url.replace("SECRET",secret);
        url = url.replace("JSCODE",code);
        String result = HttpUtils.doGet(url);
        Code2Session code2Session = JSONArray.parseObject(result,Code2Session.class);
        return code2Session;
    }

    @Override
    public WechatUser getWechatUserByOpenId(String openid) {
        return wechatUserMapper.selectUserByOpenId(openid);
    }

    @Override
    public int insertWechatUser(WechatUser user) {
        return wechatUserMapper.insert(user);
    }

    @Override
    public int updateWechatUser(WechatUser user) {
        return wechatUserMapper.updateByPrimaryKeySelective(user);
    }
}
